package com.xunmall.wechat.util.wechat;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.xunmall.base.util.DateUtils;
import com.xunmall.base.util.HttpClientUtils;
import com.xunmall.base.util.JsonUtils;
import com.xunmall.wechat.model.AccessToken;
import com.xunmall.wechat.model.JsSdkTicket;
import com.xunmall.wechat.model.WeChatQRCode;
import com.xunmall.wechat.model.WeChatUserInfo;
import com.xunmall.wechat.model.constant.WeChatLinkConstant;
import com.xunmall.wechat.model.constant.WeChatURLConstant;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.xunmall.wechat.util.URLUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class WeChatGlobalUtils {
    /**
     * 获取 全局access_token
     *
     * @param appId
     * @param appSecret
     * @return
     * @throws IOException
     */
    public static AccessToken getAccessToken(String appId, String appSecret) {
        String url = WeChatURLConstant.TOKEN_URL.replace("APP_ID", appId).replace("APP_SECRET", appSecret);
        String[] temp = url.split("\\?");
        String result = HttpClientUtils.sendGet(temp[0], temp[1]);
        Map<String, Object> map = JsonUtils.fromJson(result);
        Number err_code = (Number) map.get("errcode");
        if (err_code != null) {
            String err_msg = (String) map.get("errmsg");
            throw new RuntimeException("错误代码：" + err_code + "  错误信息： " + err_msg);
        }
        String access_token = (String) map.get("access_token");
        Number expires_in = (Number) map.get("expires_in");
        AccessToken accessToken = new AccessToken();
        accessToken.setAccessToken(access_token);
        accessToken.setExpiresIn(expires_in.intValue());
        accessToken.setDate(DateUtils.now());
        return accessToken;
    }

    /**
     * 初始化创建菜单
     *
     * @param accessToken
     * @param params
     */
    public static boolean createMenu(String accessToken, String params) {
        String url = WeChatURLConstant.CREATE_MENU_URL.replace("ACCESS_TOKEN", accessToken);
        String result = HttpClientUtils.sendPost(url, params);
        System.out.println(result);
        Map<String, Object> map = JsonUtils.fromJson(result);
        Number err_code = (Number) map.get("errcode");
        String err_msg = (String) map.get("errmsg");
        if (err_code.intValue() != 0 && !"ok".equals(err_msg)) {
            System.out.println("错误代码：" + err_code + "  错误信息： " + err_msg);
            return false;
        }
        return true;
    }

    /**
     * 根据token和openId拉取用户信息
     *
     * @return
     * @throws IOException
     * @throws JsonMappingException
     * @throws JsonParseException
     */
    public static WeChatUserInfo getUserInfo(String token, String openId) {
        String url = WeChatURLConstant.GET_USER_INFO_URL.replace("accessToken", token).replace("openId", openId);
        String[] temp = url.split("\\?");
        String result = HttpClientUtils.sendGet(temp[0], temp[1]);
        WeChatUserInfo authBean = JsonUtils.toObject(result, WeChatUserInfo.class);
        if (authBean.getOpenid() != null) {
            return authBean;
        }
        return authBean;
    }

    /**
     * 获取平台回调的所有ip列表
     *
     * @param accessToken
     * @return
     */
    public static List<String> getCallBackUrlIps(String accessToken) {
        String url = WeChatURLConstant.CALL_BACK_IPS_URL.replace("ACCESS_TOKEN", accessToken);
        String[] temp = url.split("\\?");
        String result = HttpClientUtils.sendGet(temp[0], temp[1]);
        Map<String, Object> map = JsonUtils.fromJson(result);
        List<String> list = (List<String>) map.get("ip_list");
        if (list != null && list.size() > 0) {
            return list;
        }
        return null;
    }

    /**
     * 获取页面分享js临时ticket
     *
     * @param accessToken
     * @return
     */
    public static JsSdkTicket getJSTicket(String accessToken) {
        String url = WeChatURLConstant.GET_JS_TICKET_URL.replace("ACCESS_TOKEN", accessToken);
        String[] temp = url.split("\\?");
        String result = HttpClientUtils.sendGet(temp[0], temp[1]);
        Map<String, Object> map = JsonUtils.fromJson(result);
        String ticket = (String) map.get("ticket");
        Number expiresIn = (Number) map.get("expires_in");
        JsSdkTicket jsSdkTicket = new JsSdkTicket();
        jsSdkTicket.setTicket(ticket);
        jsSdkTicket.setExpiresIn(expiresIn.intValue());
        jsSdkTicket.setDate(DateUtils.now());
        return jsSdkTicket;
    }

    /**
     * 功能描述:  静默登陆获取openId
     * @params: [appId, appSecret, code]
     * @return: java.lang.String
     * @Author: wangyanjing
     * @Date: 2019/1/17 16:30
    **/
    public static String getQuietOpenId(String appId, String appSecret, String code) {
        String url = WeChatURLConstant.QUIET_LOGIN_OPEN_ID_URL.replace("APP_ID", appId).replace("APP_SECRET", appSecret).replace("CODE", code);
        String[] temp = url.split("\\?");
        String result = HttpClientUtils.sendGet(temp[0], temp[1]);
        Map<String, Object> map = JsonUtils.fromJson(result);
        Number err_code = (Number) map.get("errcode");
        if (err_code != null) {
            String err_msg = (String) map.get("errmsg");
            throw new RuntimeException("错误代码：" + err_code + "  错误信息： " + err_msg);
        }
        String openid = (String) map.get("openid");
        return openid;
    }

    /**
     * 创建临时带参数二维码
     *
     * @param accessToken
     * @param scene_str
     * @param expireSeconds
     * @return
     * @expireSeconds 该二维码有效时间，以秒为单位。 最大不超过2592000（即30天），此字段如果不填，则默认有效期为30秒。
     */
    public static String createTempTicket(String accessToken, String expireSeconds, String scene_str) {
        WeChatQRCode wxQRCode = null;
        Map<String, String> intMap = new HashMap<String, String>();
        intMap.put("scene_str", scene_str);
        Map<String, Map<String, String>> mapMap = new HashMap<String, Map<String, String>>();
        mapMap.put("scene", intMap);

        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("expire_seconds", expireSeconds);
        paramsMap.put("action_name", WeChatLinkConstant.QR_STR_SCENE);
        paramsMap.put("action_info", mapMap);
        String data = new Gson().toJson(paramsMap);

        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(WeChatURLConstant.CREATE_TICKET_URL)
                .append("?access_token=")
                .append(accessToken);
        data = HttpClientUtils.sendPost(urlBuilder.toString(), data);
        try {
            wxQRCode = new Gson().fromJson(data, WeChatQRCode.class);
        } catch (JsonSyntaxException e) {
            wxQRCode = null;
            e.printStackTrace();
        }
        return wxQRCode == null ? null : wxQRCode.getTicket();
    }

    /**
     * 创建永久带参数二维码
     *
     * @param accessToken
     * @param scene_str
     * @return
     */
    public static String createLongTicket(String accessToken, String scene_str) {
        WeChatQRCode wxQRCode = null;
        Map<String, String> intMap = new HashMap<String, String>();
        intMap.put("scene_str", scene_str);
        Map<String, Map<String, String>> mapMap = new HashMap<String, Map<String, String>>();
        mapMap.put("scene", intMap);
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("action_name", WeChatLinkConstant.QR_LIMIT_STR_SCENE);
        paramsMap.put("action_info", mapMap);
        String data = new Gson().toJson(paramsMap);
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(WeChatURLConstant.CREATE_TICKET_URL)
                .append("?access_token=")
                .append(accessToken);
        data = HttpClientUtils.sendPost(urlBuilder.toString(), data);
        try {
            wxQRCode = new Gson().fromJson(data, WeChatQRCode.class);
        } catch (JsonSyntaxException e) {
            wxQRCode = null;
            e.printStackTrace();
        }
        return wxQRCode == null ? null : wxQRCode.getTicket();
    }

    /**
     * 根据ticket换取二维码链接
     *
     * @param ticket
     * @return
     */
    public static String showQrcode(String ticket) {
        Map<String, String> params = new TreeMap<String, String>();
        params.put("ticket", URLUtil.urlEncode(ticket, "UTF-8"));
        String showqrcode_path1 = null;
        try {
            showqrcode_path1 = URLUtil.setParmas(params, WeChatURLConstant.SHOW_QR_CODE_URL, "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return showqrcode_path1;
    }

    /**
     * 长链接转短链接接口
     *
     * @param accessToken
     * @param LongUrl
     * @return
     */
    public static String convertLong2ShortUrl(String accessToken, String LongUrl) {
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("access_token", accessToken);
        paramsMap.put("action", "long2short");
        paramsMap.put("long_url", LongUrl);
        String data = new Gson().toJson(paramsMap);
        StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append(WeChatURLConstant.CONVERT_LINK_SHORT_URL)
                .append("?access_token=")
                .append(accessToken);
        String result = HttpClientUtils.sendPost(urlBuilder.toString(), data);
        Map<String, String> map = JsonUtils.toMap(result);
        return map.isEmpty() ? "" : map.get("short_url");
    }
}
